<?php


namespace common\helpers;


use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class QiniuApi
{
    public $ak = "";//七牛云Ak
    public $sk = "";//七牛云SK
    public $bucket = "";//七牛云空间
    public $domain = "";//七牛云域名
    public $prefix = "";//文件前缀
    public $suffix = "";//文件后缀
    protected $token;

    public function __construct($ak, $sk, $bucket, $domain, $suffix = 'png', $prefix = '')
    {
        $this->ak = $ak;
        $this->sk = $sk;
        $this->bucket = $bucket;
        $this->domain = $domain;
        $this->prefix = $prefix;
        $this->suffix = $suffix;
        $auth = new Auth($this->ak, $this->sk);
        $this->token = $auth->uploadToken($this->bucket);
    }

    /**
     * 上传
     * @return array
     * @throws \Exception
     */
    public function run($filePath)
    {
        $uploadMgr = new UploadManager();
        $fileName = $this->prefix . '_' . date('YmdHis') . rand(1, 100000).'.'.$this->suffix;
        list($ret, $error) = $uploadMgr->putFile($this->token, $fileName, $filePath);
        if ($error) {
            return commonApi::message('上传失败' . $fileName, false);
        }
        return commonApi::message('上传成功', true, ['path' => $this->domain . '/' . $ret['key']]);
    }

    /**
     * 删除
     * @return array
     */
    public function delete($filePath)
    {
        $auth = new Auth($this->ak, $this->sk);
        $pathinfo = pathinfo($filePath);
        $config = new \Qiniu\Config();
        $bucketManager = new BucketManager($auth, $config);
        $err = $bucketManager->delete($this->bucket, $pathinfo['basename']);
        if (empty($err[0]) && empty($err[1])) {
            return commonApi::message('删除成功');
        }
        return commonApi::message('删除失败', false);
    }

    /**
     * 删除多个
     * @return array
     */
    public function delAll($filePaths)
    {
        $auth = new Auth($this->ak, $this->sk);
        $config = new \Qiniu\Config();
        $bucketManager = new BucketManager($auth, $config);
        $success = 0;
        $fail = 0;
        $fail_data = [];
        $success_data = [];
        foreach ($filePaths as $file) {
            $pathinfo = pathinfo($file['value']);
            $err = $bucketManager->delete($this->bucket, $pathinfo['basename']);
            if (empty($err[0]) && empty($err[1])) {
                $success++;
                $success_data[] = $file['id'];
            } else {
                $fail++;
                $fail_data[] = $file['id'];
            }
        }
        return commonApi::message("删除失败：成功{$success}条，失败{$fail}条", true, ['success' => $success_data, 'fail' => $success_data]);
    }
}